#include <iostream>
#include "App.h"

using namespace JDL;
using namespace std;

App::App(int size_x, int size_y)
{
  if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) != -1)
    {
      if ((_screen = SDL_SetVideoMode(size_x, size_y, 0, SDL_DOUBLEBUF)) != NULL)
	this->Init();
      else
	fprintf(stderr, "Error : %s", SDL_GetError());
    }
  else
    fprintf(stderr, "Error : %s", SDL_GetError());
}

App::~App()
{
  list<Drawable*>::iterator	it;

  for (it = _objs.begin(); it != _objs.end(); it++)
    {
      delete *it;
    }
  if (_icon != NULL)
    SDL_FreeSurface(_icon);
  delete _input;
  delete _framerate;
  _objs.clear();
  Mix_Quit();
  TTF_Quit();
  SDL_Quit();
}

void			App::RenderFrame()
{
  list<Drawable*>::iterator	it;

  SDL_BlitSurface(_fond, NULL, _screen, NULL); 
  for (it = _objs.begin(); it != _objs.end(); it++)
    (*it)->Render(_screen);
  this->UpdateEvent();
  _input->Update();
  SDL_Flip(_screen);
}

void			App::UpdateEvent()
{
  SDL_PollEvent(&_event);
}

bool			App::isQuit()
{
  if (_event.type == SDL_QUIT)
    return (true);
  return (false);
}

bool			App::isResize()
{
  if (_event.type == SDL_VIDEORESIZE)
    return (true);
  return (false);
}

Input			*App::GetInput()
{
  return (_input);
}

SDL_Event		App::GetEvent() const
{
  return (_event);
}

SDL_Rect		App::GetSize() const
{
  return (_size);
}

void			App::AddObject(Drawable *obj)
{
  _objs.push_back(obj);
}

void			App::SetFramerate(int fps)
{
  SDL_setFramerate(_framerate, fps);
}

int			App::GetFramerate() const
{
  return (SDL_getFramerate(_framerate));
}

void			App::SetIcon(const std::string str)
{
  SDL_Surface		*icon;

  icon = IMG_Load(str.c_str());
  if (icon == NULL)
    fprintf(stderr, "Error : %s", SDL_GetError());
  else
    SDL_WM_SetIcon(icon, NULL);
}

void			App::SetTitle(const std::string str)
{
  SDL_WM_SetCaption(str.c_str(), NULL);
}

void			App::Init()
{
  if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 1024) == -1)
    fprintf(stderr, "Error %s", Mix_GetError());
  if (TTF_Init() == -1)
    fprintf(stderr, "Error %s", SDL_GetError());
  _framerate = new FPSmanager;
  _icon = NULL;
  _input = new Input(&_event);
  SDL_initFramerate(_framerate);
  SDL_setFramerate(_framerate, 60);
  Mix_AllocateChannels(32);
  _fond = SDL_CreateRGBSurface(SDL_HWSURFACE, 1920, 1080, 32, 0, 0, 0, 0);
  SDL_FillRect(_fond, NULL, SDL_MapRGB(_fond->format, 0, 0, 0));
}
